var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index.js');
var usersRouter = require('./routes/users.js');
// 引入jwt
const jwt = require('./pem/jwt.js')
var app = express();
let verifyTokenWhite = ['/users/login','/users/addUser']
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));



// catch 404 and forward to error handler



app.use((req,res,next)=>{
	res.setHeader("Access-Control-Allow-Origin",'*')
	res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, token");
	if(verifyTokenWhite.indexOf(req.path)<0){
		  let token = req.headers.token
		  // 验证【解析】token
		  let result = new jwt(token).verifyToken()	
		  if (result.name == 'TokenExpiredError') {// 如果返回结果的name属性是TokenExpiredError，则说明token已超时
		  	  res.send({"code":403,"msg":"token超时"})
		  } else if (result.name == 'JsonWebTokenError') { // 如果返回结果是JsonWebTokenError，则说明token不对
		  	  res.send({"code":403,"msg":"token错误"})
		  } else { // 如果正确解析了数据对象，将数据对象赋值给data，继续执行
			next()
		  }
	}else{
		next()
	}
})


app.use('/', indexRouter);
app.use('/users', usersRouter);

app.use(function(req, res, next) {
  next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
module.exports = app;
